package com.danke.lib.pay;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import com.alipay.sdk.app.PayTask;
import com.tencent.mm.opensdk.constants.Build;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

/**
 * @author wupuquan
 * @version 1.0
 * @since 2018/12/28 17:57
 */
public class DKPayActivity extends Activity {

    public static final String EXTRA_CHARGE = "com.danke.lib.pay.DKPayActivity.CHARGE";
    public static final String SUCCESS = "success";
    public static final String FAIL = "fail";
    public static final String CANCEL = "cancel";
    public static final String INVALID = "invalid";
    public static final String UNKNOWN = "unknown";

    private String channel;
    private boolean isWXPayEntryActivity = false;
    private IDKPayWXHandler wxHandler;
    private DKPayWeb mPayWeb;

    public static void startForResult(Activity activity, String charge, int requestCode) {
        Intent intent = new Intent(activity, DKPayActivity.class);
        intent.putExtra(EXTRA_CHARGE, charge);
        activity.startActivityForResult(intent, requestCode);
    }

    public static void startForResult(Fragment fragment, String charge, int requestCode) {
        Intent intent = new Intent(fragment.getActivity(), DKPayActivity.class);
        intent.putExtra(EXTRA_CHARGE, charge);
        fragment.startActivityForResult(intent, requestCode);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (savedInstanceState != null) {
            setResult(UNKNOWN);
        } else {
            Intent intent = getIntent();
            String charge = intent.getStringExtra(EXTRA_CHARGE);
            JSONObject jsonObjCredential = null;
            if (!TextUtils.isEmpty(charge)) {
                DKPayLog.d("DKPayActivity received charge: " + charge);
                try {
                    JSONObject jsonObjCharge = new JSONObject(charge);
                    if (jsonObjCharge.has("credentialMap")) {
                        channel = jsonObjCharge.optString("payType");
                        jsonObjCredential = jsonObjCharge.optJSONObject("credentialMap");
                    } else {
                        setResult(FAIL, getString(R.string.DKPay_fail));
                    }
                } catch (JSONException e) {
                    setResult(FAIL, getString(R.string.DKPay_fail));
                }
            }

            if (jsonObjCredential != null) {
                DKPayLog.d("DKPayActivity received channel: " + channel);
                if (!DKPayChannel.contains(channel)) {
                    setResult(FAIL, getString(R.string.DKPay_fail));
                    return;
                }
                pay(jsonObjCredential);
            } else {
                // 如果credentialMap为空，表明待付金额为零(使用优惠券等情况)，此时无需调起支付，直接提示成功即可
                setResult(SUCCESS);
            }
        }
    }

    private boolean channelEquals(String compare) {
        return !TextUtils.isEmpty(compare) && TextUtils.equals(channel, compare);
    }

    private void pay(JSONObject credential) {
        if (channelEquals(DKPayChannel.WX.getChannel())) {
            wxpay(credential);
        } else if (channelEquals(DKPayChannel.ALIPAY.getChannel())) {
            alipay(credential);
        } else if (channelEquals(DKPayChannel.CMB.getChannel())) {
            cmbpay(credential);
        }
    }

    /**
     * 微信
     */
    private void wxpay(JSONObject credential) {
        DKPayLog.d("DKPayActivity start wx credential : " + credential);
        String appId = credential.optString("appId");
        wxHandler = new DKPayWXHandler(this, appId);
        if (!wxHandler.isWXAppInstalled()) {
            setResult(INVALID, getString(R.string.DKPay_app_not_installed, "微信"));
        } else {
            boolean isSupport = wxHandler.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
            if (isSupport) {
                wxHandler.launch(credential);
            } else {
                setResult(FAIL, getString(R.string.DKPay_wx_app_not_support));
            }
        }
    }

    /**
     * 支付宝
     */
    private void alipay(JSONObject credential) {
        DKPayLog.d("DKPayActivity start alipay credential : " + credential);
        final String orderInfo = credential.optString("orderInfo");
        new Thread(new Runnable() {
            @Override
            public void run() {
                PayTask payTask = new PayTask(DKPayActivity.this);
                DKPayLog.d("alipaysdk version: " + payTask.getVersion());
                final Map<String, String> result = payTask.payV2(orderInfo, true);
                DKPayLog.d("DKPayActivity alipay result: " + result);
                // {resultStatus=9000,
                //  result={"alipay_trade_app_pay_response":{"code":"10000","msg":"Success","app_id":"2015121000952778","auth_app_id":"2015121000952778","charset":"utf-8","timestamp":"2018-12-27 18:04:09","out_trade_no":"11000563","total_amount":"0.01","trade_no":"2018122722001434880532197662","seller_id":"2088911119736808"},"sign":"glFK8liNXJYNu3MXWn+11lTby5UpgxxT/TiDGB2SFH0BTbgrjOE7CeCk6zTdUejBCGDVkvcCcPdKd2qYrN4xwo/NzHrITNtQps+LDHjHzF1zM++b7QNWDY434WOy3RqI2q9DyQZpAGpmwrtrisXue++j/eN9/uSv4BBWmzO5kDk=","sign_type":"RSA"},
                //  memo=}
                DKPayActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        String resultInfo = "";
                        if (result.containsKey("result")) {
                            resultInfo = result.get("result");
                        }
                        String resultStatus = "";
                        if (result.containsKey("resultStatus")) {
                            resultStatus = result.get("resultStatus");
                        }
                        String memo = "";
                        if (result.containsKey("memo")) {
                            memo = result.get("memo");
                        }
                        if (resultStatus == null) {
                            resultStatus = "";
                        }
                        switch (resultStatus) {
                            case "9000": // 支付成功
                                setResult(SUCCESS);
                                break;
                            case "6001": // 用户中途取消
                                setResult(CANCEL, "user_cancelled");
                                break;
                            default: // 各种失败
                                setResult(FAIL, getString(R.string.DKPay_fail), memo);
                                break;
                        }
                    }
                });
            }
        }).start();
    }

    /**
     * 招行一网通
     */
    private void cmbpay(JSONObject credential) {
        mPayWeb = new DKPayCmbWeb(this, credential);
    }

    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        DKPayLog.d("onNewIntent isWXPayEntryActivity=" + this.isWXPayEntryActivity);
        // 微信
        if (wxHandler != null) {
            setIntent(intent);
            wxHandler.onNewIntent(intent);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    public void setResult(String pay_result) {
        setResult(pay_result, "");
    }

    public void setResult(String pay_result, String error_msg) {
        setResult(pay_result, error_msg, "");
    }

    public void setResult(String pay_result, String error_msg, String extra_msg) {
        DKPayLog.d("setResultAndFinish result=" + pay_result + " isWXPayEntryActivity=" + this.isWXPayEntryActivity);
        Intent intent = new Intent();
        intent.putExtra("pay_result", pay_result);
        intent.putExtra("error_msg", error_msg);
        intent.putExtra("extra_msg", extra_msg);
        this.setResult(RESULT_OK, intent);
        this.finish();
    }

    @Override
    public void onBackPressed() {
        if (mPayWeb != null && mPayWeb.canGoBack()) {
            mPayWeb.goBack();
            return;
        }
        setResult(CANCEL);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mPayWeb != null) {
            mPayWeb.onResume();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mPayWeb != null) {
            mPayWeb.onPause();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mPayWeb != null) {
            mPayWeb.onDestroy();
        }
    }
}
